package com.sxhuayuan.parking.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxhuayuan.parking.compenent.RabbitMQConfig;
import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.config.PayStatus;
import com.sxhuayuan.parking.entity.Order;
import com.sxhuayuan.parking.entity.ParkingLot;
import com.sxhuayuan.parking.plugin.parking.ParkingPlugin;
import com.sxhuayuan.parking.plugin.parking.che_an.CheAnParkingPlugin;
import com.sxhuayuan.parking.plugin.parking.result.QueryParkingFeeResultWrap;
import com.sxhuayuan.parking.queue.msg.QueueMsg;
import com.sxhuayuan.parking.service.OrderService;
import com.sxhuayuan.parking.service.ParkingLotService;
import com.sxhuayuan.parking.service.PluginService;
import com.sxhuayuan.parking.socket.ChannelGroupPool;
import com.sxhuayuan.parking.utils.SettingUtils;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;

/** 后端管理系统进入页*/
/** 这里面的地址和iview-admin 路由地址要一一对应 不然将访问不到 */
@Controller
public class IndexController {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private CacheManager cacheManager;
	@Autowired
	private PluginService pluginService;
	@Autowired
	RabbitTemplate rabbitTemplate;
	@Autowired
	AmqpTemplate amqpTemplate;
	@Autowired
	ChannelGroupPool parkingLotInterface;
	@Autowired
	ThreadPoolTaskExecutor taskExecutor;
	@Autowired
	OrderService orderService;
	@Autowired
	ParkingLotService lotService;

	/**
	 * code: 404 mes: "" type: "ajax" url:
	 */
	@RequestMapping("/save_error_logger")
	@ResponseBody
	public RespMessage saveErrorLogger(HttpServletRequest request, @RequestBody Map<String, String> map) {
		StringBuilder msg = new StringBuilder();
		map.forEach((e, v) -> {
			msg.append(e).append("=").append(v).append("\n");
		});
		log.debug("访问出错: {}", msg);
		return RespMessage.success();
	}

	/**
	 * 打印记录错误信息
	 */
	@RequestMapping("/log_error")
	@ResponseBody
	public RespMessage logError(HttpServletRequest request, String err) {
		try {
			if (err == null) {
				err = IOUtils.toString(request.getInputStream(), "utf-8");
			}
			log.debug("访问出错: {}", err);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return RespMessage.success();
	}

	@RequestMapping("/vadmin")
	public String vadmin() {
		return "index/index";
	}

	@RequestMapping("/vagent")
	public String vadminOther() {
		return "index/index";
	}

	@RequestMapping("/testcache")
	@ResponseBody
	public String cache() {
		Ehcache ehcache = cacheManager.getEhcache("parkingLotOrder");
		List<String> keys = ehcache.getKeys();
		if (keys != null) {
			for (String key : keys) {
				log.debug(key);
			}
		}
		return "success";
	}

	@RequestMapping("/testplugin")
	@ResponseBody
	public String testPlugin(String lotSn) {
		ParkingPlugin plugin = pluginService.getParkingPlugin(CheAnParkingPlugin.ID);
		return plugin.execute("/api.aspx/park.out.controllers", lotSn, null);
	}

	@RequestMapping("/testorder")
	@ResponseBody
	public RespMessage testPaySuccess(String sn) {
		if (SettingUtils.get().getIsDebug()) {
			Order order = orderService.findBySn(sn);
			if (Objects.isNull(order)) {
				return RespMessage.validError();
			}
			if (order.getPayStatus() == PayStatus.success) {
				return RespMessage.error("order is already paid");
			}
			orderService.paySuccess(order, "test" + System.currentTimeMillis());
			return RespMessage.success();
		}
		return RespMessage.noPermissionError();
	}

	@RequestMapping("/testpush")
	@ResponseBody
	public String testPush() {
		// rabbitTemplate.convertAndSend("delay_queue_park_partnerpay", "test msg");
		try {
			MessageProperties properties = MessagePropertiesBuilder.newInstance().setContentType("application/json").build();
			QueueMsg qm = new QueueMsg();
			qm.setBody("{\"name\":\"haha1\", \"test\":{\"a\":\"b\"}, \"arr\":[\"a\", 4]}");
			qm.setRetryPlan(new Integer[] { 2, 4, 6, 8, 10 });
			qm.setId(RandomUtils.nextLong());
			Message msg = MessageBuilder.withBody(qm.getBytes()).setHeader("x-delay", 0).build();
			rabbitTemplate.send(RabbitMQConfig.EXCHANGE_DELAY_START, RabbitMQConfig.QUEUE_PARK_IN, msg);

			// Message msg2 =
			// MessageBuilder.withBody("{\"name\":\"haha2\"}".getBytes()).andProperties(properties).setHeader("x-delay",
			// 1000).build();
			// rabbitTemplate.send(RabbitMQConfig.EXCHANGE_DELAY,
			// RabbitMQConfig.QUEUE_PARTNERPAY, msg2);
			//
			// Message msg3 =
			// MessageBuilder.withBody("{\"name\":\"haha3\"}".getBytes()).andProperties(properties).setHeader("x-delay",
			// 2000).build();
			// rabbitTemplate.send(RabbitMQConfig.EXCHANGE_DELAY,
			// RabbitMQConfig.QUEUE_PARTNERPAY, msg3);

			// rabbitTemplate.convertAndSend("queue_delay", messagePostProcessor);
		} catch (AmqpException e) {
			e.printStackTrace();
		}
		return "success";
	}

	@RequestMapping("/testparkinglotsocketinterface")
	@ResponseBody
	public RespMessage testParkingLotInterface(String pluginId, String carPlate, String lotSn) {
		ParkingLot lot = lotService.findBySn(lotSn);
		if (lot != null) {
			ParkingPlugin plugin = pluginService.getParkingPlugin(lot.getPluginId());
			QueryParkingFeeResultWrap queryParkingFee = plugin.queryParkingFee(lot, carPlate);
			return RespMessage.success(queryParkingFee);
		}
		return RespMessage.error("车场未找到");
	}
}
